package org.example.short_link.admin.service.ServiceImpl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.example.short_link.admin.common.biz.user.UserContext;
import org.example.short_link.admin.common.convention.result.Result;
import org.example.short_link.admin.dao.entity.GroupDO;
import org.example.short_link.admin.dao.mapper.GroupMapper;
import org.example.short_link.admin.dto.req.ShortLinkGroupSortReqDTO;
import org.example.short_link.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import org.example.short_link.admin.dto.resp.ShortLinkGroupRespDTO;
import org.example.short_link.admin.remote.ShortLinkRemoteService;
import org.example.short_link.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import org.example.short_link.admin.service.GroupService;
import org.example.short_link.admin.toolkit.RandomGenerator;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;


/**
 * 短链接分组接口实现类
 */
@Service
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper,GroupDO> implements GroupService{

    // TODO : 后续重构为 SpringCould Field调用
    ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService(){

    };

    @Override
    public void SaveGroup(String groupName) {
        SaveGroup(UserContext.getUsername(), groupName);

    }

    @Override
    public void SaveGroup(String username, String groupName) {
        String gid;
        do{
            //生成6位随机数
            gid = RandomGenerator.generateRandom();
        }while (!hasGid(username ,gid));
        GroupDO groupDO = GroupDO.builder()
                .gid(gid)
                .sortOrder(0)
                .username(username)
                .name(groupName)
                .build();
        baseMapper.insert(groupDO);
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        LambdaQueryWrapper<GroupDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .orderByDesc(GroupDO::getSortOrder,GroupDO::getUpdateTime);
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = shortLinkRemoteService
                .ShortLinkCount(groupDOList.stream().map(GroupDO::getGid).toList());
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);
        shortLinkGroupRespDTOList.forEach((each) -> {
            Optional<ShortLinkGroupCountQueryRespDTO> first = listResult.getData()
                    .stream().
                    filter(item -> Objects.equals(item.getGid(), each.getGid())).
                    findFirst();
            first.ifPresent(item -> each.setShortLinkCount(first.get().getShortLinkCount()));
        });
        return shortLinkGroupRespDTOList;
    }




    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        LambdaQueryWrapper<GroupDO> updateWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid())
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setName(requestParam.getName());
        baseMapper.update(groupDO,updateWrapper);


    }


    @Override
    public void deleteGroup(String gid) {
        LambdaQueryWrapper<GroupDO> deleteWrappers = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getDelFlag, 0);
        GroupDO groupDO = new GroupDO();
        groupDO.setDelFlag(1);
        baseMapper.update(groupDO,deleteWrappers);

    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        requestParam.forEach(each -> {
            GroupDO groupDO = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, UserContext.getUsername())
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getDelFlag, 0);
            baseMapper.update(groupDO , queryWrapper);



        });
    }

    private boolean hasGid(String username , String gid){
        LambdaQueryWrapper<GroupDO> queryWrapper = new LambdaQueryWrapper<>();
        // TODO : 设置用户名
        queryWrapper.eq(GroupDO::getGid , gid).eq(GroupDO::getUsername , username);
        GroupDO hasGroupFlag = baseMapper.selectOne(queryWrapper);
        return hasGroupFlag == null;
    }






}
